package com.zho.common.server;

import java.util.Enumeration;
import javax.servlet.ServletContext;
import org.springframework.web.context.WebApplicationContext;

public class SpringUtils {
    private static WebApplicationContext springContext = null;

    /**
     * 
     * @param beanName
     * @return
     * @throws SystemException
     */
    public static Object getBean(String beanName) throws Exception {
        WebApplicationContext ctx = findSpringContext();
        return ctx.getBean(beanName);
    }

    /**
     * 
     * @return
     * @throws SystemException
     */
    public static WebApplicationContext findSpringContext() throws Exception {
        if (springContext != null) {
            return springContext;
        }
        springContext = findSpringContext(ServerConfig.getServletContext());
        return springContext;
    }

    /**
     * 
     * @param servletContext
     * @return
     * @throws SystemException
     */
    public static WebApplicationContext findSpringContext(ServletContext servletContext) throws Exception {
        if (servletContext != null) {
            Enumeration enum1 = servletContext.getAttributeNames();
            Object key, value;
            while (enum1.hasMoreElements()) {
                try {
                    key = enum1.nextElement();
                    value = servletContext.getAttribute((String) key);
                    if (value instanceof WebApplicationContext) {
                        return (WebApplicationContext) value;
                    }
                } catch (Exception e) {
                }
            }
        }
        throw new Exception();
    }
}
